package rsj.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.util.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rsj.properties.DownLoadProperties;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static common.util.http.HttpUtil.createJSONHeader;

public class HttpService {
    private static final HttpService instance = new HttpService();
    private static final Logger logger = LoggerFactory.getLogger(HttpService.class);

    public static HttpService getInstance() {
        return instance;
    }

    private static DownLoadProperties downLoadProperties;

    public static void setDownLoadProperties(DownLoadProperties downLoadProperties) {
        HttpService.downLoadProperties = downLoadProperties;
    }

    public static void main(String[] args) {
        System.out.println(getUpDownToken("123123","tid"));
    }

    public static String getUpDownToken(String userId, String $tid) {
        String body = createBody(userId, $tid);
        Map<String, String> headers = createJSONHeader();
        String response = doPostHttp(body, headers);
        return doHandlerRes(response);
    }

    private static String doHandlerRes(String response) {
        return String.valueOf(JSON.parseObject(response).getObject("_data_", JSONObject.class).get("File_Token"));
    }

    private static String doPostHttp(String body, Map<String, String> headers) {
        try {
            String upDownLoadUrl = downLoadProperties.getUpDownLoadUrl();
            return HttpUtil.post(upDownLoadUrl , body, headers);

//            String url = "http://192.168.1.27:9095/file/getFileAccessToken";
//            logger.info(url + "body ::" + body);
//            return HttpUtil.post(url
//                    , body, headers);

        } catch (IOException e) {
            logger.error("http请求获取token失败！", e);
            throw new RuntimeException("http请求获取token失败！");
        }

//        return "{\"$status\": \"1\",\"$tid\": \"TID_721DEBCD7A564E5DA16DE789E4836B43\",\"$msg\": \"获取成功\",\"_data_\": {\"File_Token\": \"99hfuiosjdu3giqhhgi8ju\",}}";
    }

    private static String createBody(String userId, String $tid) {

        Map<String,String> _data_ = new HashMap<>();
        _data_.put("User_Id", userId);

        Map<String,Object> $json = new HashMap<>();
        $json.put("$tid", $tid);
        $json.put("$api", downLoadProperties.getUpDownApi());
        $json.put("$appid", downLoadProperties.getUpDownAppId());
        //$json.put("$api", PropUtils.getProperties("upDownApi"));
        //$json.put("$appid", PropUtils.getProperties("upDownAppId"));
        $json.put("_data_",_data_);

//        Map<String,Object> body = new HashMap<>();
//        body.put("$json", $json);
        logger.info("createBody::param:{}", JSON.toJSONString($json));

        return JSON.toJSONString($json);
    }
}
